
package com.jf.cloud.product.controller.multishop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jf.cloud.api.multishop.feign.ShopUserFeignClient;
import com.jf.cloud.api.multishop.vo.ShopUserVO;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.product.constant.StockBillType;
import com.jf.cloud.common.product.constant.StockType;
import com.jf.cloud.common.product.vo.StockBillLogItemVO;
import com.jf.cloud.common.product.vo.StockBillLogVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.ExcelUtil;
import com.jf.cloud.product.bo.mongo.MongoStockBillLogBO;
import com.jf.cloud.product.dto.StockBillLogDTO;
import com.jf.cloud.product.service.StockBillLogService;
import com.jf.cloud.product.vo.StockBillInLogExcelVO;
import com.jf.cloud.product.vo.StockBillLogExcelVO;
import com.jf.cloud.product.vo.StockBillOutLogExcelVO;
import com.jf.cloud.product.vo.mongo.MongoStockBillLogVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import ma.glasnost.orika.MapperFacade;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * 出入库明细
 *
 * @author zz
 * @date 2022-06-22 17:14:22
 */
@RestController("multishopStockBillLogController")
@RequestMapping("/m/stock_bill_log")
@Tag(name = "出入库明细")
public class StockBillLogController{

    @Autowired
    private StockBillLogService stockBillLogService;

    @Autowired
    private ShopUserFeignClient shopUserFeignClient;

    @Autowired
    private MapperFacade mapperFacade;

    @GetMapping("/page")
    @Operation(summary = "获取出入库明细列表" , description = "分页获取出入库明细列表")
    public ServerResponseEntity<PageVO<MongoStockBillLogBO>> page(@Valid PageDTO pageDTO,@ParameterObject StockBillLogDTO stockBillLogDTO ) {
        stockBillLogDTO.setShopId(AuthUserContext.get().getTenantId());
        PageVO<MongoStockBillLogBO> stockBillLogPage = stockBillLogService.page(pageDTO, stockBillLogDTO);
        return ServerResponseEntity.success(stockBillLogPage);
    }

    @GetMapping("/info/{stockBillLogId}" )
    @Operation(summary = "获取出入库明细" , description = "根据stockBillLogId获取出入库明细")
    public ServerResponseEntity<MongoStockBillLogVO> getByStockBillLogId(@PathVariable("stockBillLogId") Long stockBillLogId) {
        return ServerResponseEntity.success(stockBillLogService.getByStockBillLogId(stockBillLogId));
    }

    @PostMapping
    @Operation(summary = "保存出入库明细" , description = "保存出入库明细")
    public ServerResponseEntity<Void> save(@Valid @RequestBody StockBillLogVO stockBillLogVO) {
        //出库操作下判断出库数是否超出库存数？执行出库 ： 返回错误消息
        if (stockBillLogVO.getType() == 1) {
            List<StockBillLogItemVO> stockBillLogItems = stockBillLogVO.getStockBillLogItems();
            for (int i = 0; i < stockBillLogItems.size(); i++) {
                if (stockBillLogItems.get(i).getStockCount() > stockBillLogItems.get(i).getStock()) {
                    throw new LuckException("出库数超出库存数");
                }
            }
        }
        stockBillLogVO.setShopId(AuthUserContext.get().getTenantId());
        stockBillLogVO.setEmployeeId(AuthUserContext.get().getUserId());
        Long userId = AuthUserContext.get().getUserId();
        ServerResponseEntity<ShopUserVO> userResponse = shopUserFeignClient.getByUserId(userId);
        if (!userResponse.isSuccess() || userResponse.getData() == null) {
            throw new LuckException("无法获取制单人手机号");
        }
        stockBillLogVO.setMakerMobile(userResponse.getData().getPhoneNum());
        if (!Objects.equals(stockBillLogVO.getStockBillType(), StockBillType.PURCHASE_STORAGE.value())) {
            stockBillLogVO.setStockBillType(Objects.equals(stockBillLogVO.getType(), StockType.OUT_OF_STOCK.value()) ? StockBillType.OTHER_OUTBOUND.value() : StockBillType.OTHER_STORAGE.value());
        }
        stockBillLogService.saveInfo(stockBillLogVO);
        return ServerResponseEntity.success();
    }


    @PutMapping
    @Operation(summary = "更新出入库明细" , description = "更新出入库明细")
    public ServerResponseEntity<Void> update(@Valid @RequestBody StockBillLogDTO stockBillLogDTO) {
        if (Objects.isNull(stockBillLogDTO.getStockBillLogId())) {
            throw new LuckException("id不能为空");
        }
        stockBillLogService.updateInfo(stockBillLogDTO);
        return ServerResponseEntity.success();
    }

    @GetMapping("/exportStockBillLog")
    @Operation(summary = "导出出入库明细列表", description ="导出出入库明细列表" )
    public void exportStockBillLog(StockBillLogDTO stockBillLogDTO, HttpServletResponse response) {
        stockBillLogDTO.setShopId(AuthUserContext.get().getTenantId());
        List<StockBillLogExcelVO> stockBillLogList = stockBillLogService.exportStockBillLogList(stockBillLogDTO);
        // 出/入库分开导出
        if (stockBillLogDTO.getType() == 1) {
            List<StockBillOutLogExcelVO> excelData = JSON.parseObject(
                    JSON.toJSONString(stockBillLogList),
                    new TypeReference<List<StockBillOutLogExcelVO>>(){}
            );
            ExcelUtil.soleExcel(response, excelData,
                    StockBillOutLogExcelVO.EXCEL_NAME,
                    StockBillOutLogExcelVO.MERGE_ROW_INDEX,
                    StockBillOutLogExcelVO.MERGE_COLUMN_INDEX,
                    StockBillOutLogExcelVO.class
            );
        } else {
            List<StockBillInLogExcelVO> excelData = JSON.parseObject(
                    JSON.toJSONString(stockBillLogList),
                    new TypeReference<List<StockBillInLogExcelVO>>(){}
            );
            ExcelUtil.soleExcel(response, excelData,
                    StockBillInLogExcelVO.EXCEL_NAME,
                    StockBillInLogExcelVO.MERGE_ROW_INDEX,
                    StockBillInLogExcelVO.MERGE_COLUMN_INDEX,
                    StockBillInLogExcelVO.class
            );
        }
    }

    @PutMapping("/voided")
    @Operation(summary = "作废出入库明细单" , description = "作废出入库明细单")
    public ServerResponseEntity<Void> voided(@RequestParam("stockBillLogId") Long stockBillLogId) {
        Long shopId = AuthUserContext.get().getTenantId();
        stockBillLogService.voided(shopId, stockBillLogId);
        return ServerResponseEntity.success();
    }
}
